<?php

namespace app\admin\command;

use think\Cache;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\Loader;
use think\Db;

class Deerhome extends Command
{

    protected function configure()
    {
        $this->setName('deerhome')->addOption('action', 'a', Option::VALUE_REQUIRED, 'action name', null);
    }

    protected function execute(Input $input, Output $output)
    {
        $action = $input->getOption('action') ?: '';
        if(!method_exists($this,$action)){
            $output->error("[Deerhome->{$action}] action not found!");
            return;
        }
        $this->$action();
    }

   /**
     * 定时取消订单
     * 保留1个小时
     */
    protected function cancel()
    {
        //1个小时前
        $time=date("Y-m-d H:i:s",time()-1*3600);

        //次卡订单::超时未支付
        $cardOrderModel=new \app\admin\model\deerhome\CardOrder;
        $cardOrderModel->where('add_time',"<",$time)->where("status",1)->update(["status"=>3]);
        //次卡订单::已到期
        $cardOrderModel->where('end_time',"<",date("Y-m-d H:i:s"))
        ->where("status",2)
        ->update([
            "status"=>3
            ,"num_left"=>0
            ,"done_time"=>date("Y-m-d H:i:s")
        ]);

        //过期优惠券
        $YhqModel=new \app\admin\model\deerhome\Yhq;
        $YhqModel->where('end_day',"<",date("Y-m-d"))->where("status","in",[1,2])->update(["status"=>4]);
        
        //作废充值流水
        Db::name("deerhome_order_pay_log")->where('add_time',"<",$time)->where("type",2)->where("is_wallet",1)->where("status",1)->update(["status"=>3,"note"=>"长时间未支付，交易关闭"]);
        $orderArr=Db::name("deerhome_order")->where("status",1)->where('time_add',"<",$time)->column("status,sn","id");
        if(count($orderArr)==0){
            echo "\n cancel:0 \n";
            return;
        }
        $time=date("Y-m-d H:i:s");
        $logArr=[];
        foreach($orderArr as $id=>$item){
            $logArr[]=[
                'order_id'=>$id,
                'add_time'=>$time,
                'ac_user'=>'系统',
                'note'=>"长时间未支付，交易关闭"
            ];
        }
        $orderIds=array_keys($orderArr);
        $order_snArr=[];
        foreach($orderArr as $id=>$item){
            $order_snArr[]=$item['sn'];
        }
   
        Db::startTrans();
        try{
            //作废流水
            Db::name("deerhome_order_pay_log")->where("order_sn","in",$order_snArr)->update(["status"=>3,"note"=>"长时间未支付，交易关闭"]);
            Db::name("deerhome_order")->where("id","in",$orderIds)->update(["status"=>8,"time_done"=>$time]);
            Db::name("deerhome_order_log")->insertAll($logArr);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            echo "\n ERR-cancel:".$e->getMessage()." \n";
            return;
        }
        echo "\n cancel:".count($orderArr)." \n";
        return;
    }
   
    /**
     * 服务订单，自动验收
     * 前一天申请验收的订单
     */
    protected function yanshou()
    {
        $orders=Db::name("deerhome_order")
        ->where("worker_apply_time","<",date("Y-m-d")." 00:00:00")
        ->where("status",4)
        ->where("order_type",1)
        ->where("price_need_pay",Db::raw("price_payed"))
        ->update([
            "status"=>5
            ,"time_done"=>date("Y-m-d H:i:s")
        ]);
        echo 'yanshou:'.$orders." \n";
        return;
    }
    /**
     * 定时结算分成给服务人员
     */
    protected function money()
    {
        $orders=Db::name("deerhome_order")->field("id,jz_user_id,sn,worker_id,worker_price,worker_price_note")->where("order_type",1)->where("worker_id",">",0)->where("status",5)->where("worker_price_to_wallet",0)->limit(1000)->select();
        if(count($orders)==0){
            echo 'done.money'." \n";
            return;
        }
        foreach ($orders as $key => $item) {
            Db::startTrans();
            try{
                Db::name("deerhome_order")->where("id",$item['id'])->update(["worker_price_to_wallet"=>1]);
                Db::name("deerhome_worker_money_log")->insert([
                    'type'=>"服务分成",
                    'jz_worker_id'=>$item['worker_id'],
                    'jz_order_sn'=>$item['sn'],
                    'price'=>$item['worker_price'],
                    'note'=>"系统结算：".$item['worker_price_note'],
                    'status'=>2,
                    'sh_ren'=>'系统',
                    'addtime'=>date("Y-m-d H:i:s"),
                    'donetime'=>date("Y-m-d H:i:s")
                ]);
                Db::name("deerhome_worker")->where("id",$item['worker_id'])
                ->update([
                    "money_dj"=>Db::raw("money_dj-".$item['worker_price'])
                    ,"money_left"=>Db::raw("money_left+".$item['worker_price'])
                ]);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                echo "\n ERR-money:ID-{$item['id']}:".$e->getMessage()." \n";
            }
            //会员升级
            try{
                \Tools\UserAndAgentLev::actionUserById($item['jz_user_id']);
            }catch(\Exception $e){
                echo "\n ERR-money-lev-update:ID-{$item['id']}:".$e->getMessage()."-line:".$e->getLine()." \n";
            }
        }
        Db::name("deerhome_worker")->where("money_dj","<",0)->update(["money_dj"=>0]);
        echo "\n money:".count($orders)." \n";
        return;
    }
    /**
     * 定时结算分销分佣
     */
    protected function money_agent()
    {
        $orders=Db::name("deerhome_order")->field("id,sn,agent_lev1_uid,agent_lev1_price,agent_lev1_price_js,agent_lev1_price_note,agent_lev2_uid,agent_lev2_price,agent_lev2_price_js,agent_lev2_price_note")->where("agent_lev1_price|agent_lev2_percent",">",0)->where("status",5)->where("agent_lev1_price_js|agent_lev2_price_js",2)->limit(500)->select();
        if(count($orders)==0){
            echo 'done.money_agent'." \n";
            return;
        }
        foreach ($orders as $key => $item) {
            Db::startTrans();
            try{
                Db::name("deerhome_order")->where("id",$item['id'])->update(["agent_lev1_price_js"=>1,"agent_lev2_price_js"=>1]);
                $moneyLogArr=[];
                if($item['agent_lev1_price']>0){
                    array_push($moneyLogArr,[
                        'type'=>"分销分佣",
                        'deerhome_user_id'=>$item['agent_lev1_uid'],
                        'jz_order_sn'=>$item['sn'],
                        'price'=>$item['agent_lev1_price'],
                        'note'=>"系统结算：".$item['agent_lev1_price_note'],
                        'status'=>2,
                        'sh_ren'=>'系统',
                        'addtime'=>date("Y-m-d H:i:s"),
                        'donetime'=>date("Y-m-d H:i:s")
                    ]);
                    Db::name("deerhome_user")->where("id",$item['agent_lev1_uid'])->setInc("wallet_left",$item['agent_lev1_price']);
                }
                if($item['agent_lev2_price']>0){
                    array_push($moneyLogArr,[
                        'type'=>"分销分佣",
                        'deerhome_user_id'=>$item['agent_lev2_uid'],
                        'jz_order_sn'=>$item['sn'],
                        'price'=>$item['agent_lev2_price'],
                        'note'=>"系统结算：".$item['agent_lev2_price_note'],
                        'status'=>2,
                        'sh_ren'=>'系统',
                        'addtime'=>date("Y-m-d H:i:s"),
                        'donetime'=>date("Y-m-d H:i:s")
                    ]);
                    Db::name("deerhome_user")->where("id",$item['agent_lev2_uid'])->setInc("wallet_left",$item['agent_lev2_price']);
                }
                Db::name("deerhome_worker_money_log")->insertAll($moneyLogArr);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                echo "\n ERR-money_agent:ID-{$item['id']}:".$e->getMessage()."-line:".$e->getLine()." \n";
            }
            //推广人升级
            try{
                \Tools\UserAndAgentLev::actionAgentById($item['agent_lev1_uid']);
            }catch(\Exception $e){
                echo "\n ERR-money_agent-lev-update:OID-{$item['id']}:".$e->getMessage()."-line:".$e->getLine()." \n";
            }
        }
        echo "\n money_agent:".count($orders)." \n";
        return;
    }
    /**
     * 定时结算积分
     */
    protected function jf()
    {
        $orders=Db::name("deerhome_order")->field("id,sn,jz_user_id,price_payed")->where("jf_js",0)->where("status",5)->limit(500)->select();
        if(count($orders)==0){
            echo 'done.jf'." \n";
            return;
        }
        $addtime=date("Y-m-d H:i:s");
        foreach ($orders as $key => $item) {
            Db::startTrans();
            try{
                $jf=ceil($item['price_payed']);
                Db::name("deerhome_user")->where("id",$item['jz_user_id'])->setInc("jf",$jf);
                Db::name("deerhome_user_jf_log")->insert([
                    "deerhome_user_id"=>$item['jz_user_id'],
                    "jf"=>$jf,
                    "order_sn"=>$item['sn'],
                    "note"=>"系统结算",
                    "addtime"=>$addtime
                ]);
                Db::name("deerhome_order")->where("id",$item['id'])->update(["jf_js"=>1]);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                echo "\n ERR-jf:ID-{$item['id']}:".$e->getMessage()."-line:".$e->getLine()." \n";
            }
        }
        echo "\n jf:".count($orders)." \n";
        return;
    }
}
